package a1;

import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class TitledSpinnerSliderPanel extends JPanel implements ChangeListener{
	private JSlider slider;
	private JSpinner spinner;

	/**
	 * Needed since JPanel is Serializable
	 */
	private static final long serialVersionUID = 2554337418494724467L;
	
	TitledSpinnerSliderPanel(String title) {
		super();
	
		this.slider = makeSlider();
		this.slider.addChangeListener(this);
		
		this.spinner = makeSpinner();
		this.spinner.addChangeListener(this);
		
		this.setBorder(new TitledBorder(BorderFactory.createEtchedBorder(), title));
		
		this.add(slider);
		this.add(spinner);
		
		
	}
	
	private JSpinner makeSpinner() {
		// TODO Auto-generated method stub
		JSpinner spinner = new JSpinner();
		spinner.setModel( new SpinnerNumberModel(Constants.MIN_COLOR_VALUE, // initial value
                               Constants.MIN_COLOR_VALUE, 		// min
                               Constants.MAX_COLOR_VALUE, 		// max
                               Constants.SPINNER_INCREMENT));	// step
		
		return spinner;
	}

	private JSlider makeSlider() {
		// TODO Auto-generated method stub
	    JSlider slider = new JSlider();
	    //slider.setBorder(BorderFactory.createTitledBorder(title));
	    slider.setMaximum(Constants.MAX_COLOR_VALUE);
	    slider.setMinimum(Constants.MIN_COLOR_VALUE);
	    slider.setValue(Constants.MIN_COLOR_VALUE);
	    slider.setMajorTickSpacing(Constants.SLIDER_MAJOR_TICK_SPACING);
	    slider.setMinorTickSpacing(Constants.SLIDER_MINOR_TICK_SPACING);
	    slider.setPaintTicks(true);
	    slider.setPaintLabels(true);
	    
		return slider;
	}

	@Override
	public void stateChanged(ChangeEvent e) {
		// TODO Auto-generated method stub

		Object source = e.getSource();
		
		if (source instanceof JSlider) {
			// if slider changes, we update the spinner to match
			this.spinner.setValue(((JSlider) source).getValue());
		} else if (source instanceof JSpinner) {
			// if spinner changes, we update slider to match
			this.slider.setValue(Integer.parseInt(	((JSpinner) source).getValue().toString()
								));
		}
		
		// Fire out a property change so the JPanel that contains this 
		// JPanel knows to update it's preview for the color
		this.firePropertyChange(Constants.COLOR_UPDATE_EVENT, false, true);
		
		// update the preview panel with new color
		//RGBSliderChooserPanel.updatePreview();
	}
	
	public int getValue() {
		return this.slider.getValue();
	}
	
	public void setValue(int value) {
		this.slider.setValue(value);
	}

}
